﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GameDataTempshitEditor
{
    public partial class SaveList : Form
    {
        public SaveList()
        {
            InitializeComponent();
        }

        private class TreeNode_DirtyObject : TreeNode
        {
            public Red.GameData.Raw.DataObject _Object;

            public TreeNode_DirtyObject(Red.GameData.Raw.DataObject obj, string name)
                : base(name)
            {
                _Object = obj;
                ImageIndex = 1;
                SelectedImageIndex = 1;
            }
        }

        private class TreeNode_DirtyFile : TreeNode
        {
            public Red.GameData.Raw.DataFile _File;

            public TreeNode_DirtyFile(Red.GameData.Raw.DataFile file)
                : base(file.Path)
            {
                _File = file;
                ImageIndex = 0;
                SelectedImageIndex = 0;                
            }

            public void AddObject( Red.GameData.Raw.DataObject obj, string name)
            {
                Nodes.Add(new TreeNode_DirtyObject(obj, name));
            }
        }

        public DialogResult SaveChanges(Red.GameData.EditorEnvironment env)
        {
            // get modified object
            var objects = env.Data.ModifiedObjects;
            if (objects.Count == 0)
                return DialogResult.Yes; // no changes

            // group objects per file
            var fileNodes = new Dictionary<Red.GameData.Raw.DataFile, TreeNode_DirtyFile>();
            foreach (var dirtyObject in objects)
            {
                TreeNode_DirtyFile treeNode = null;
                fileNodes.TryGetValue(dirtyObject.File, out treeNode);

                if (treeNode == null)
                {
                    treeNode = new TreeNode_DirtyFile(dirtyObject.File);
                    fileNodes[dirtyObject.File] = treeNode;
                    treeNode.Expand();
                }

                var name = Red.GameData.Raw.Utils.GetObjectNameSafe(env.Reflection, dirtyObject);
                treeNode.AddObject(dirtyObject, name);
            }

            // finish
            foreach (var file in fileNodes.Values)
            {
                treeView1.Nodes.Add(file);
            }

            // show the window
            return ShowDialog();
        }
    }
}
